from flask import Flask, g
from flask import abort
from flask import request
from flask import Blueprint, current_app
from utils import get_real_addr
from collections import defaultdict
from datetime import timedelta
import json
import requests
import time
import config
import os

LOG = config.getlogger()
golia = Blueprint('golia', __name__)
url_mapping = {}
url_update_time = 0


def update_url_mapping():
    global url_mapping
    global url_update_time
    mapping = {}
    for u in config.GOLIA_URLS:
        r = requests.get(u)
        if r.status_code == 200:
            try:
                for ip in json.loads(r.text):
                    mapping[ip] = u
            except Exception, ex:
                pass
    url_mapping = mapping
    url_update_time = int(time.time())


@golia.route('/<ip>/<head>', methods=['GET'])
def dispatch(ip=None, head=None):
    if len(url_mapping) == 0 or url_update_time - int(time.time()) > 3600:
        update_url_mapping()
    try:
        u = url_mapping[ip]
        if u is None:
            abort(404)
        show = request.args.get('show', '')
        newurl = os.path.join(u, ip, head)
        if show != '':
            newurl = newurl + '?show=' + show
        r = requests.get(newurl)
        if r.status_code == 200:
            return r.text
        else:
            abort(404)
    except Exception, ex:
        print ex
        LOG.error('error: %s', str(ex))
        abort(500)
